package com.kqzz.common.exception;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.google.gson.Gson;
import com.kqzz.common.api.response.Response;

import lombok.extern.slf4j.Slf4j;

/**
 * 登录失败处理
 */
@Slf4j
@Component("customAuthFailHandler")
public class CustomAuthFailHandler extends SimpleUrlAuthenticationFailureHandler {
	
	@Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) 
    		throws IOException, ServletException {
		System.out.println(request.getParameter("username"));
		log.info("");
		String message = "";
		if(!StringUtils.isBlank(request.getHeader("x-requested-with")) 
        		&& request.getHeader("x-requested-with").equals("XMLHttpRequest")){ // 判断客户端为ajax请求			
			response.setStatus(HttpStatus.OK.value());
			response.setContentType("application/json;charset=UTF-8");
			if(exception instanceof BadCredentialsException || exception instanceof UsernameNotFoundException){
				Gson gson = new Gson();
				message = "登录失败，请核对账号或密码"; // "用户名或密码错误";
				response.getWriter().write(gson.toJson(new Response().failure(message)));
			}
		}else{
    		if(exception instanceof BadCredentialsException || exception instanceof UsernameNotFoundException){
    			request.setAttribute("msg", exception.getMessage());
    		}else{
    			request.setAttribute("msg", "登录失败，请核对后登录");
    		}
//        		String savedRequestUrl = Base64.decodeStr(request.getParameter("callbackurl"));
    		request.setAttribute("callbackurl", request.getParameter("callbackurl"));
    		request.getRequestDispatcher("/returnLogin").forward(request, response);
		}
	}
}
